<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\BaseController;
use app\common\controller\Backend;
use think\Exception;
use \think\facade\Cache;
use \app\admin\model\Config as ConfigModel;


class Config extends Backend
{
    public function initialize() {
        parent::initialize();
        $this->_mod  = new \app\admin\model\Config();
    }

    public function index($type='index')
    {
        $this->_mod  = new \app\admin\model\Config();
        $data = $this->_mod->field('name,value')->select();
        foreach ($data as $key=>$val) {
            $val_data = $val->value;
            $web_config[$val->name] = @unserialize($val_data)?unserialize($val_data):$val_data;
        }
        return view($type,['web_config'=>$web_config]);
    }


    /**
     * 批量保存配置
     */
    public function edit(){
        $config = input('post.setting');
        try {
            if($config && is_array($config)){
                foreach ($config as $name => $value) {
                    $map = ['name' => $name];
                    if(is_array($value)){
                        $value=serialize($value);
                    }
                    $result = $this->_mod->where($map)->save(['value' => $value]);
                }
            }
            $data = success(1,'修改成功','');
        }catch (Exception $e){
            $data = fail(0,'修改失败','');
        }
        cache('web_config',null);
        return $data;
    }

    public function ajax_mail_test() {
        // print_r($_POST);die;
        $email = $this->_get('email', 'trim');
        !$email && $this->ajaxReturn(0);
        //发送
        $mailer = mailer::get_instance();
        if ($mailer->send($email, L('send_test_email_subject'), L('send_test_email_body'))) {
            $this->ajaxReturn(1);
        } else {
            $this->ajaxReturn(0);
        }
    }
}




